<script src="/libs/vue/vue.js"></script>
<script src="/libs/moment/moment-with-locales.min.js"></script>
<script src="/libs/moment/moment-timezone-with-data-2012-2022.js"></script>
<script src="/libs/axios/axios.min.js"></script>
<script src="/libs/antd/antd-with-locales.js"></script>
<script src="/libs/jsencrypt/jsencrypt.js"></script>

<script>
    const publicKey = '{{ config('vars.rsa_pub_key') }}'
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(publicKey)
</script>

<script>
    var profCategories = {!! json_encode(config('vars.prof_categories'), JSON_UNESCAPED_UNICODE) !!};

    var Workflow = {
        data: {
            phases: []
        },

        methods: {
            reloadWorkflowPhases() {
                axios.get('/api/common/get-workflow-phases').then(response => {
                    if (response.data.ok) {
                        this.phases = response.data.phases
                    }
                })
            },
            atPhases(phaseIds, largeGroupId = 0) {
                largeGroupId = largeGroupId !== null ? Number(largeGroupId) : 0;
                for (let phaseId of phaseIds) {
                    for (let phase of this.phases) {
                        if (phaseId === phase.phase_id && largeGroupId === phase.large_group_id
                            && phase.has_begun && !phase.has_ended) {
                            return true
                        }
                    }
                }
                return false
            },
            notAtPhases(phaseIds, largeGroupId = 0) {
                return !this.atPhases(phaseIds, largeGroupId)
            },
        }
    }
</script>

<script>
    function megSuccess(msg) {
        antd.message.success(msg)
    }

    function megWarn(msg) {
        antd.message.warn(msg)
    }

    function megError(msg) {
        antd.message.error(msg)
    }

    function megLoading(msg) {
        antd.message.loading(msg, 0)
    }

    function megDestroy() {
        antd.message.destroy()
    }

    function loading(message) {
        antd.message.loading(message, 0)
    }

    function dismiss() {
        antd.message.destroy()
    }

    function info(message) {
        antd.message.info(message)
    }

    function success(message) {
        antd.message.success(message)
    }

    function warn(message) {
        antd.message.warn(message)
    }

    function error(message) {
        antd.message.error(message)
    }

    function subset(obj, keys) {
        var result = {}
        if (obj != null) {
            keys.forEach(key => {
                if (obj.hasOwnProperty(key)) {
                    result[key] = obj[key]
                }
            })
        }
        return result
    }

    function parseUrl(url) {
        var a = document.createElement('a');
        a.href = url;
        // var a = new URL(url);
        return {
            source: url,
            protocol: a.protocol.replace(':', ''),
            host: a.hostname,
            port: a.port,
            query: a.search,
            params: (function () {
                var params = {},
                    seg = a.search.replace(/^\?/, '').split('&'),
                    len = seg.length,
                    p;
                for (var i = 0; i < len; i++) {
                    if (seg[i]) {
                        p = seg[i].split('=');
                        params[p[0]] = decodeURIComponent(p[1]);
                    }
                }
                return params;
            })(),
            hash: a.hash.replace('#', ''),
            path: a.pathname.replace(/^([^\/])/, '/$1')
        };
    }

    function handleHeaderDropdownItemClick({key}) {
        if (key == 'change-password') {
            this.changePasswordDialogVisible = true
        } else if (key == 'logout') {
            location = '/logout'
        }
    }

    function handleChangePassword() {
        let {password, passwordConfirm} = this.passwordInfo
        if (!password) return this.$message.error("请填写密码")
        if (password.length < 8 || password.length > 16) return this.$message.error("密码长度应为8-16位")
        if (!passwordConfirm) return this.$message.error("请确认密码")
        if (password != passwordConfirm) return this.$message.error("两次填写密码不一致")
        let encryptedText = encrypt.encrypt(password)
        this.$message.loading('正在处理', 0)
        this.$axios.post("/api/auth/change-password", {
            password: encryptedText
        }).then(res => {
            this.$message.destroy()
            this.changePasswordDialogVisible = false
            console.log(res)
            if (res.data.ok) {
                this.$message.success("密码修改成功")
            } else {
                this.$message.error(res.data.message)
            }
        })
    }

    var globalRowKeySeed = 1

    function copyFieldValueFromObject(tplObj, dataObj, arrayElementDefs) {
        for (var key in tplObj) {
            if (dataObj.hasOwnProperty(key)) {
                if (Array.isArray(tplObj[key])) {
                    if (Array.isArray(dataObj[key]) && dataObj[key].length) {
                        if (arrayElementDefs.hasOwnProperty(key)) {
                            var elementKeys = Object.keys(arrayElementDefs[key])
                            dataObj[key].forEach(item => {
                                var element = {...arrayElementDefs[key]}
                                element.key = globalRowKeySeed++
                                copyFieldValueFromObject(element, item, {})
                                tplObj[key].push(element)
                            })
                        }
                    }
                } else if (typeof tplObj[key] === 'object' && tplObj[key] !== null) {
                    // console.log('copying obj', key, dataObj[key])
                    copyFieldValueFromObject(tplObj[key], dataObj[key], arrayElementDefs)
                } else {
                    // console.log('copying', key, dataObj[key])
                    tplObj[key] = dataObj[key]
                }
            }
        }
    }


    axios.interceptors.response.use(response => {
        console.log('Response:', response.status, response.data)
        return response
    })
</script>